﻿/*!
*  $.netpost jQuery Extension v1.0.0
* http://netpost.codeplex.com/
*
* Released under the MIT license
* http://netpost.codeplex.com/license
*
*/

(function ($, window) {

    var NetpostClass = function() {};

    NetpostClass.prototype = function () {
        var doSetup = function () {
            // prefilter for JSON to APS.NET serialization ($.post option: {contentType: 'net.object'})
            $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
                // Modify options, control originalOptions, store jqXHR, etc
                if ("object" == typeof (originalOptions) && "net.object" == originalOptions.contentType) {
                    // serialize data using repacked oroginal object
                    options.data = $.param(toNetObject(originalOptions.data));

                    options.contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
                    options.processData = false;
                    originalOptions.processData = false;
                }
            });

            // extend original jquery object with 'netpost' method
            $.extend({
                netpost: function (postConfig) {
                    // INPUT:
                    //    { url: , data: }
                    //
                    // RETURN: jqXHR

                    return $.ajax($.extend({
                        url: undefined,
                        data: {},
                        type: 'POST',
                        cache: false,
                        contentType: 'net.object'
                    }, postConfig));
                }
            });
        },
		doMakeNetCompatibleObject = function (obj, prevPath, netObject) {
		    if (undefined === prevPath) prevPath = '';
		    if (undefined === netObject) netObject = {};

		    if ("object" == typeof (obj)) {
		        for (var key in obj) {
		            if ("object" == typeof (obj[key]) || $.isArray(obj)) {
		                doMakeNetCompatibleObject(obj[key], prevPath + ($.isArray(obj) ? '[' + key + ']' : (0 < prevPath.length ? '.' : '') + key), netObject);
		            } else {
		                netObject[prevPath + (0 < prevPath.length ? '.' : '') + key] = obj[key];
		            }
		        }
		    } else {
		        netObject[prevPath] = obj;
		    }

		    return netObject;
		},
		toNetObject = function (obj) {
		    // non objects do not require serialization
		    if ("object" != typeof (obj)/* || $.isArray(obj)*/) return obj;

		    return doMakeNetCompatibleObject(obj);
		};

        // initialize class
        doSetup();
    } ();

} (jQuery, window));